package com.gec.filter;
import com.alibaba.fastjson.JSON;
import com.gec.common.BaseContext;
import com.gec.common.R;
import com.gec.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**检查是否完成登录
 *
 *
 * @author : [chenxys]
 * @version : [v1.0]
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    /**
     * 路径匹配器,支持通配符写法
     */
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 拦截特定资源,对所有的静态资源进行放行处理
     * @author chenxys
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1、获取本次请求的URI
        String requestURI = request.getRequestURI();

        // {}为占位符
       // log.info("拦截到请求:{}",requestURI);

        // 定义不需要处理的请求路径
        String[] urls = new String[]{
          "/employee/login",
          "/employee/logout",
          "/backend/**",
          "/front/**",
          "/user/sendMsg",
          "/user/login"
        };

        // 2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        // 3、如果不需要处理,则直接放行
        if (check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        // 4、判断登录状态,如果已登录,则直接放行
        if ((request.getSession().getAttribute("employee")) != null || request.getSession().getAttribute("user") != null){
            Long employeeId = (Long) request.getSession().getAttribute("employee");
            User user = (User) request.getSession().getAttribute("user");
            log.info("用户已登录,用户ID为{}",employeeId);
            // 设置当前登录用户ID
            if (!ObjectUtils.isEmpty(employeeId)){
                BaseContext.setCurrentId(employeeId);
            }
            // 设置当前登录用户ID
            if (!ObjectUtils.isEmpty(user)){
                Long userId = user.getId();
                BaseContext.setCurrentId(userId);
            }
            filterChain.doFilter(request,response);
            return;
        }

        // 5、如果未登录,则返回未登录结果 使用输出流进行返回
       // 根据前端的响应拦截器 只需code=0 && msg=NOTLOGIN即可自动跳转登录页面
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配,检查本次请求是否要放行
     * @author chenxys
     * @param requestURI 请求路径
     * @param urls 放行的请求路径
     * @return boolean
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            // 进行匹配                     放行的   请求的
            boolean match = PATH_MATCHER.match(url, requestURI);
            // 匹配上了
            if (match){
                return true;
            }
        }
        // 未匹配上
        return false;
    }
}
